package com.googlecode.weathergram;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final int SELECT_FROM_GALLERY_ACTIVITY_REQUEST_CODE = 100;
	private static final int CAPTURE_CAMERA_PHOTO_ACTIVITY_REQUEST_CODE = 200;
	private static final int CROP_ACTIVITY_REQUEST_CODE = 300;

	private Intent weather;
	private Uri currentMediaUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		checkPrerequisites();

		weather = new Intent(this, WeatherService.class);
		startService(weather);

		Button selectFromGallery = (Button) findViewById(R.id.selectFromGallery);
		Button captureCameraPhoto = (Button) findViewById(R.id.captureCameraPhoto);

		selectFromGallery.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK,
						Media.EXTERNAL_CONTENT_URI);
				intent.setType("image/*");

				startActivityForResult(intent,
						SELECT_FROM_GALLERY_ACTIVITY_REQUEST_CODE);
			}
		});

		captureCameraPhoto.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

				startActivityForResult(intent,
						CAPTURE_CAMERA_PHOTO_ACTIVITY_REQUEST_CODE);
			}
		});
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (weather != null)
			stopService(weather);
	}

	private void checkPrerequisites() {
		NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting())
			showSettingsDialog(getString(R.string.main_networkTitle),
					getString(R.string.main_networkMessage),
					Settings.ACTION_WIRELESS_SETTINGS);

		if (!((LocationManager) getSystemService(LOCATION_SERVICE))
				.isProviderEnabled(LocationManager.GPS_PROVIDER))
			showSettingsDialog(getString(R.string.main_gpsTitle),
					getString(R.string.main_gpsMessage),
					Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	}

	private void showSettingsDialog(String title, String message,
			final String settings) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle(title);
		dialog.setMessage(message);

		dialog.setPositiveButton(getString(R.string.main_settingsButton),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(settings);
						MainActivity.this.startActivity(intent);
					}
				});
		dialog.setNegativeButton(getString(R.string.main_cancelButton),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		dialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAPTURE_CAMERA_PHOTO_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// Image captured and saved to fileUri specified in the Intent
				currentMediaUri = data.getData();
				startCropActivity();
			} else if (resultCode == RESULT_CANCELED) {
				// User cancelled the image capture
				Toast.makeText(this, R.string.main_imageCaptureCancel,
						Toast.LENGTH_SHORT).show();
			} else {
				// Image capture failed, advise user
				Toast
						.makeText(this, R.string.main_imageCaptureFail, Toast.LENGTH_SHORT)
						.show();
			}
		}

		if (requestCode == SELECT_FROM_GALLERY_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				currentMediaUri = data.getData();
				startCropActivity();
			}
		}

		if (requestCode == CROP_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Bundle extras = data.getExtras();
					currentMediaUri = ImageHelper.saveImage(
							(Bitmap) extras.getParcelable("data"), "cropped");
				} else
					Toast.makeText(this, R.string.main_cropFailed, Toast.LENGTH_SHORT)
							.show();

				startShareActivity();
			}
		}
	}

	private void startCropActivity() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(currentMediaUri, "image/*");

		intent.putExtra("aspectX", 1000);
		intent.putExtra("aspectY", 1000);

		intent.putExtra("outputX", 1000);
		intent.putExtra("outputY", 1000);

		intent.putExtra("crop", true);
		intent.putExtra("scale", true);

		intent.putExtra("noFaceDetection", true);
		intent.putExtra("return-data", true);
		try {
			MainActivity.this.startActivityForResult(intent,
					CROP_ACTIVITY_REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, R.string.main_cropFailed, Toast.LENGTH_SHORT).show();
			startShareActivity();
		}
	}

	private void startShareActivity() {
		if (currentMediaUri != null) {
			Intent intentShare = new Intent(getApplicationContext(),
					ShareActivity.class);
			intentShare.putExtra("mediaUri", currentMediaUri.toString());

			MainActivity.this.startActivity(intentShare);
		}
	}
}
